package com.callbell.cas.filter;

import com.callbell.cas.util.MD5Util;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class MyFilter extends  HandlerInterceptorAdapter {

    private JdbcTemplate jdbcTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       String rs = request.getMethod();
       System.out.println(rs);

        response.setContentType("application/json");

        String appid = request.getParameter("appid");
        String timestamp = request.getParameter("timestamp");
        String sign = request.getParameter("sign");
        String mtype = request.getParameter("mtype");
        List<Map<String, Object>> list = jdbcTemplate.queryForList("SELECT str FROM inter_keywork WHERE compenont_num = ?", appid);

        if (list.size() >= 1){
            String str = (String) list.get(0).get("str");
            String plainText = str+"appid"+appid+"mtype"+mtype+"timestamp"+timestamp+str;
            String md5str = MD5Util.encryption(plainText);
            System.out.println(plainText);
            if (md5str.equals(sign)){
                System.out.println("authentication success");
                return true;
            }
        }
        System.out.println("authentication failed");
        response.getWriter().write("{\"status\":0,\"msg\":\"authentication failed\"}");
        return false;
    }

    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }


}
